<script setup lang="ts">
import '../assets/home.css'
import useApi from '../useApi';
import { ref } from 'vue'
import Decimal from 'decimal.js'
import msgModal from '../components/msgModal.vue'
import CustomConfirm from './CustomConfirm.vue'
import NumericKeyboard from './NumericKeyboard.vue'  
import { Search, Delete, ShoppingCart, Wallet, Money, Upload, Document, Present } from '@element-plus/icons-vue'
const msgModalRef = ref(msgModal);
const showModal = (title,times=1000) => {
	if(msgModalRef.value){
		msgModalRef.value.openMsg(title,times);
	}
}
setInterval(() => {
    getZitiOrder();
},60000)
let mp31 = new Audio('https://aiweijian.com/source/tip.mp3');  // 创建音频对象 
const getZitiOrder = async() => {
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "GET"
    };
    let res:any = await useApi('index/getDistriOrder',options); 
    if(res.code == 2){
        mp31.play();
    }
}
const printPort = () => {
    if(isNewOrder.value == false){
        return;
    }
    if(payModel.value == 2){
        paytype.value = 3;
    }
    let decMoney = new Decimal(0);
    if(userId.value>0){
        if(payModel.value == 4 || isBpay.value == 2){
            //现金支付：payModel.value == 4(会员充值) isBpay.value == 2(现金支付)
            decMoney = new Decimal(userMoney.value);
        }else{
            decMoney = new Decimal(userMoney.value).sub(new Decimal(allPrice.value));
        }
        if(decMoney< new Decimal(0)){
            decMoney = new Decimal(0);
        }
    }
    let printData = ref({});
    let printAllNum = new Decimal(0),printAllPrice = new Decimal(0);
    printAllNum= allNum.value;
    printAllPrice = allPrice.value;
    if(payModel.value == 4){
        printData.value[0] = {
                id:0,
                title:'充值',
                num:rechargeNum.value,
                price:rechargeNum.value,
                vipPrice:rechargeNum.value,
                thisAllPrice:rechargeNum.value
        };
        printAllNum = new Decimal(rechargeNum.value);
        printAllPrice = new Decimal(rechargeNum.value);
        if(rechargeGiveNum.value != ''){
            printData.value[1] = {
                    id:0,
                    title:'赠送',
                    num:rechargeGiveNum.value,
                    price:rechargeGiveNum.value,
                    vipPrice:rechargeGiveNum.value,
                    thisAllPrice:rechargeGiveNum.value
            };
        }
        decMoney = decMoney.add(new Decimal(rechargeNum.value));
        if(decMoney< new Decimal(0)){
            decMoney = new Decimal(0);
        }
        rechargeNum.value = '';
        rechargeGiveNum.value = '';
    }else{
        printData.value = cartList.value;
    }
    payModel.value = 1;
    let thisDateObj = new Date();
    let dateStr = thisDateObj.getFullYear()+'-'+(thisDateObj.getMonth()+1)+'-'+thisDateObj.getDate()+' '+thisDateObj.getHours()+':'+thisDateObj.getMinutes()+':'+thisDateObj.getSeconds();
    let userPhoneStr = ref('');
    if(userId.value>0){
        userPhoneStr.value = phoneNum.value.slice(0, 3) + '****' + phoneNum.value.slice(7);
    }else{
        userPhoneStr.value = '无';
    }
    isNewOrder.value = false;
    if(isBpay.value == 2){
        //现金收款
        paytype.value = -1;
    }
    window.electron.ipcRenderer.send('print',JSON.stringify(printData.value),localStorage.getItem('title'),printAllNum.toString(),printAllPrice.toString(),orderNumber.value,paytype.value,userId.value,decMoney.toString(),dateStr,userPhoneStr.value);
}
const{ SerialPort }= require('serialport')
const port1 = new SerialPort({
    path: 'COM1', // 串口号
    baudRate: 9600, // 波特率
    autoOpen: true, // 是否自动打开端口
}, function (err) {
if (err) {
    return console.log('打开失败: ', err.message)
}
    console.log('打开成功')
})
let ifInput = ref(false),zeroCount = ref(0);
setInterval(() => {
    ifInput.value = !ifInput.value;
},500)
// 用于存储分段接收的数据
let bufferCache = Buffer.alloc(0);
let nowPart='';
port1.on('data', function (data) {
    zeroCount.value++;
    // 将新接收的数据追加到缓存中
    bufferCache = Buffer.concat([bufferCache, data]);
    const bufferStr = bufferCache.toString('utf-8');
    console.log('当前缓存数据:', bufferStr);

    //提取整体斤两
    const match2 = bufferStr.match(/(\d+\.\d+)(?:kg|g)/i);
    if (!match2) return;
    nowPart = match2[1];
    console.log('now:',nowPart);
    if(nowPart){
        try {
	    	let weightValue = '';
	    	weightValue = nowPart;
	        if (weightValue) {
	            // 转换为Decimal对象
	            let rawWeight = new Decimal(weightValue);
	            
	            // 根据称的单位进行转换 (假设称输出的是千克，需要转换为斤)
	            // 1千克 = 2斤
	            let weightInJin = rawWeight.mul(2);
	            
	            // 保留三位小数
	            let multiplier = new Decimal(10).pow(3);
	            let formattedWeight = weightInJin.mul(multiplier).round().div(multiplier);
	            
	            // 验证数值有效性并更新状态
	            if (formattedWeight.gt(new Decimal(0)) && ifInput.value) {
	                zeroCount.value = 0;
	                goodNumFromPort.value = formattedWeight;
	                console.log('处理后的称重数据(斤):', goodNumFromPort.value.toString());
	            }
	        }
            bufferCache = Buffer.alloc(0);
	    } catch (error) {
            console.error('称重数据解析错误:', error, '原始数据:', bufferStr);
            // 出错时也清空缓存
            bufferCache = Buffer.alloc(0);
            nowPart = '';
        }
    }
    // 超过一定时间没有有效数据，重置为零
    if (zeroCount.value >= 40) {
        goodNumFromPort.value = new Decimal(0);
        // 同时清空缓存和部分数据
        bufferCache = Buffer.alloc(0);
        nowPart = '';
    }
})
let cate:any = ref({});
let goodList:any = ref({});
let memberSearchShow = ref(false);
let phoneNum = ref('');
let userTitle = ref('暂无信息'),userMoney = ref(0),userGiveMoney = ref(0),userId = ref(0),userIfRecharge = ref(0);
let deleteGoodIndex = ref(-1);
let paytype = ref(1);//1：微信支付 2：支付宝支付
let qcode = ref('');
let orderNumber = ref('');
let isPaying = ref(false);
let payModel = ref(1); //结算模式 1正常 2会员 3代付 4充值
let isBpay = ref(1);//会员支付是否代付 1普通 2代付
let orderGiveMoney = ref('');
let userPayPassword = ref('');
let cateId = ref(0);
let cartList:any = ref({}),allNum = ref(new Decimal(0)),allPrice = ref(new Decimal(0)),allListNum = ref(0),rechargeNum = ref(''),rechargeInputType = ref(1),rechargeGiveNum = ref(''),goodNumFromPort = ref(new Decimal(0.1));
let balanceNum = ref(new Decimal(0));
let moneyNum = ref(new Decimal(0));
let mp3 = new Audio('https://aiweijian.com/source/tick.mp3');  // 创建音频对象 
let moneyPayType = ref(1); //现金支付模式  1：现金支付 2：会员充值
// 添加CustomConfirm相关的状态
let confirmVisible = ref(false);
let confirmTitle = ref('');
let confirmMessage = ref('');
let confirmType = ref(0); // 1: 删除单个商品, 2: 清空所有商品, 3: 现金结算, 4: 现金充值, 5: 组合支付
const countPaySure = () =>{
    if(isBpay.value == 2){
        balanceNum.value = new Decimal(userMoney.value);
        moneyNum.value = allPrice.value.sub(new Decimal(userMoney.value));
        payModel.value = 1;
        rechargeInputType.value = 5;
        memberSearchShow.value = true;
    }else{
        balanceNum.value = new Decimal(userMoney.value);
        moneyNum.value = allPrice.value.sub(new Decimal(userMoney.value));
        payModel.value = 5;
        rechargeInputType.value = 5;
        memberSearchShow.value = true;
    }
}
const getShopCate = async () => {
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "GET"
    };
    let res:any = await useApi('index/getCateAndGood',options); 
    if(res.code == 1){
        cate.value = res.data;
        goodList.value = cate.value[cateId.value]['goodlist'];
    }
}
// 隐藏输入框相关
const hiddenInput = ref('');
const hiddenInputRef = ref(null);

// 添加键盘事件处理函数
const handleKeyDown = (event) => {
    if (event.key === 'Enter' && hiddenInput.value) {
        // 按下回车键且输入框有值时触发处理
        initPos(hiddenInput.value);
        hiddenInput.value = '';
    }
}

// 获取焦点方法
const focusHiddenInput = () => {
    hiddenInput.value = '';
    if (hiddenInputRef.value) {
(hiddenInputRef.value as HTMLInputElement).focus();
    }
}
const initPos = async (code) =>{
    
    if(!isPaying.value){
        return;
    }
    qcode.value = code.trim();
    const headerStr = code.substring(0,2);
    if(headerStr == '28'){
        paytype.value = 2;
    }else{
        paytype.value = 1;
    }
    switch(payModel.value){
        case 1:
            //正常结算
            orderPay(1);
            break;
        case 2:
            //会员结算
            break;
        case 3:
            //代付
            orderPay(2);
            break;
        case 4:
            //会员充值
            userRecharge();
            break;
        case 5:
            //会员余额加现金结算
            userOrderPay();
            break;
    }
}

defineExpose(
	{
		getShopCate
	}
)
const changeCat = (id) => {
    cateId.value = id;
    goodList.value = cate.value[cateId.value]['goodlist'];
}
getShopCate();
const memberRecharge =  () =>  {
    isBpay.value=1;
    if(userId.value == 0){
        showModal('请先查询会员信息');
        return;
    }
    if(userIfRecharge.value == 2){
        showModal('该账户禁止充值');
        return;
    }
    isNewOrder.value = true;
    rechargeInputType.value = 2;
    rechargeNum.value = '';
    rechargeGiveNum.value = '';
    memberSearchShow.value = !memberSearchShow.value;
}
const changeSure = () => {
    if(rechargeInputType.value == 6){
        allNum.value = new Decimal(changeNum.value);
    }else if(rechargeInputType.value == 7){
        let subPrice = allPrice.value.sub(new Decimal(changeNum.value));
        if(subPrice>new Decimal(1)){
            showModal('调价不能高于1元');
            return;
        }
        allPrice.value = new Decimal(changeNum.value);
    }
    changeNum.value = '';
}
const search  = () =>{
    if(phoneNum.value.length<=0 ){
        showModal('请输入手机号');
        localStorage.removeItem('userPhone');
        return;
    }
    localStorage.setItem('userPhone',phoneNum.value);
    getUserInfo();
}
const getUserInfo = async()=>{
    let bodyData = ref({});
    bodyData.value = {
        phone:phoneNum.value
    }
    
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    
    try {
        let res:any = await useApi('index/getUserInfo',options); 
        if(res.code == 1){
            const userinfo = res.data;
            userTitle.value = userinfo.userPhone+'('+userinfo.userNickname+')';
            userMoney.value =  userinfo.userBalance;
            userGiveMoney.value =  userinfo.userGiveMoney;
            userId.value = userinfo.id;
            userIfRecharge.value = userinfo.ifRecharge;
            if(userId.value>0){
                reBuildCartList();
            }
        } else if(res.code == -1) {
            // 处理网络错误
            showModal('网络连接失败，无法获取会员信息');
        } else {
            showModal(res.msg);
        }
    } catch (error) {
        console.error('获取会员信息失败:', error);
        showModal('网络连接失败，无法获取会员信息');
    }
}
const clearUser = () => {
    userTitle.value = '';
    userMoney.value =  0;
    userGiveMoney.value =  0;
    userId.value = 0;
    phoneNum.value = '';
    cartList.value = {};
    allNum.value = new Decimal(0);
    allPrice.value = new Decimal(0);
    allListNum.value = 0;
    localStorage.removeItem('userPhone');
}
let isNewOrder = ref(false);
const goPay = (index) =>{
    isNewOrder.value = true;
    if(index != 4 && userId.value == 0){
        if(allPrice.value<=new Decimal(0)){
            showModal('请选择商品');
            return;
        }
        if(allNum.value<=new Decimal(0)){
            showModal('请选择商品');
            return;
        }
    }
    isPaying.value = true;
    if(userId.value>0){
        if(index == 1){
            if(isBpay.value == 2){
                //现金结算
                if(allPrice.value.gt(new Decimal(userMoney.value))){
                    balanceNum.value = new Decimal(userMoney.value);
                    moneyNum.value = allPrice.value.sub(new Decimal(userMoney.value));
                    
                    // 使用CustomConfirm组件
                    confirmType.value = 3;
                    confirmTitle.value = '现金结算确认';
                    confirmMessage.value = '余额不足，抵扣'+balanceNum.value.toString()+'元，现金支付剩余'+moneyNum.value.toString()+'元';
                    confirmVisible.value = true;
                }else{
                    balanceNum.value = new Decimal(0);
                    moneyNum.value = allPrice.value;
                    
                    // 使用CustomConfirm组件
                    confirmType.value = 3;
                    confirmTitle.value = '现金结算确认';
                    confirmMessage.value = '确认现金付款吗？';
                    confirmVisible.value = true;
                }
                moneyPayType.value = 1;
            }else{
                //会员结算,余额足够
                if(allPrice.value.gt(new Decimal(userMoney.value))){
                    //会员余额不足
                    balanceNum.value = new Decimal(userMoney.value);
                    moneyNum.value = allPrice.value.sub(new Decimal(userMoney.value));
                    
                    // 使用CustomConfirm组件替代countPayShow
                    confirmType.value = 5;
                    confirmTitle.value = '组合支付确认';
                    confirmMessage.value = '余额不足，抵扣'+balanceNum.value.toString()+'元，支付剩余'+moneyNum.value.toString()+'元';
                    confirmVisible.value = true;
                }else{
                    //会员结算,余额足够
                    payModel.value = 2;
                    rechargeInputType.value = 5;
                    memberSearchShow.value = true;
                    balanceNum.value = allPrice.value;
                    moneyNum.value = new Decimal(0);
                }
            }
        }
        if(index == 4){
            //会员充值
            showModal('支付中，请扫码',10000);
            focusHiddenInput();
            payModel.value = 4;
        }
    }else{
        if(index == 1){
            if(isBpay.value == 2){
                //现金结算
                // 使用CustomConfirm组件
                confirmType.value = 3;
                confirmTitle.value = '现金结算确认';
                confirmMessage.value = '确认现金付款吗？';
                confirmVisible.value = true;
                moneyPayType.value = 1;
            }else{
                //正常结算
                showModal('支付中，请扫码',10000);
                focusHiddenInput();
                payModel.value = 1;
            }
            
        }
    }
} 
const countpay = async() =>{
    showModal('支付中，请扫码',10000);
    focusHiddenInput();
    payModel.value = 5;
}
const orderPay = async(type:number)=>{
    let bodyData = ref({});
    bodyData.value = {
        paytype:paytype.value,
        qcodeNum:qcode.value,
        price:allPrice.value,
        num:allNum.value,
        goodList:JSON.stringify(cartList.value),
        isBpay:type//是否代付
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    let res:any = await useApi('index/orderPay',options);
    if(res.code == 1 || res.code == 3){ 
        orderNumber.value = res.data.orderNumber;
        startPolling();
    }else{
        showModal(res.msg);
    }
}
const orderMoneyPay = async()=>{
    let bodyData = ref({});
    bodyData.value = {
        userId:userId.value,
        paytype:5,
        price:allPrice.value,
        balanceNum:balanceNum.value,
        moneyNum:moneyNum.value,
        num:allNum.value,
        goodList:JSON.stringify(cartList.value)
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    let res:any = await useApi('index/orderMoneyPay',options);
    if(res.code == 1 || res.code == 3){ 
        orderNumber.value = res.data.orderNumber;
        showModal('结算完成');
        printPort();
        phoneNum.value = '';
        cartList.value = {};
        allPrice.value = allNum.value = new Decimal(0);
        userId.value = 0;
        userTitle.value = '暂无信息',userMoney.value = 0,userGiveMoney.value = 0;
        userPayPassword.value = '';
        clearAllData();
        memberPaying.value = false;
    }else{
        showModal(res.msg);
    }
}
const userOrderPay = async()=>{
    let bodyData = ref({});
    bodyData.value = {
        paytype:paytype.value,
        qcodeNum:qcode.value,
        price:allPrice.value,
        num:allNum.value,
        balanceNum:balanceNum.value,
        moneyNum:moneyNum.value,
        userId:userId.value,
        goodList:JSON.stringify(cartList.value)
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    let res:any = await useApi('index/countPay',options);
    if(res.code == 1 || res.code == 3){ 
        orderNumber.value = res.data.orderNumber;
        startPolling();
    }else{
        showModal(res.msg);
    }
}
let memberPaying = ref(false);
const memberGoPay = async()=>{
    let bodyData = ref({});
    if(memberPaying.value){
        return;
    }
    memberPaying.value = true;
    bodyData.value = {
        userId:userId.value,
        price:allPrice.value,
        num:allNum.value,
        goodList:JSON.stringify(cartList.value),
        password:userPayPassword.value,
        balanceNum:balanceNum.value,
        moneyNum:moneyNum.value,
        isBpay:isBpay.value
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    showModal('结算中，请稍后',10000);
    let res:any = await useApi('index/memberPay',options); 
    if(res.code == 1){
        orderNumber.value = res.data.orderNumber;
        showModal('结算完成');
        printPort();
        phoneNum.value = '';
        cartList.value = {};
        allPrice.value = allNum.value = new Decimal(0);
        userId.value = 0;
        userTitle.value = '暂无信息',userMoney.value = 0,userGiveMoney.value = 0;
        userPayPassword.value = '';
        clearAllData();
        memberPaying.value = false;
    }else{
        showModal(res.msg);
        memberPaying.value = false;
    }
}
const deleteShow  = (index) =>{
    
    if(deleteGoodIndex.value == index){
        deleteGoodIndex.value = -1;
    }else{
        deleteGoodIndex.value = index;
    }
}
const deleteThisGoods = () =>{
    if(deleteGoodIndex.value == -1){
        showModal('请先选择商品');
        return;
    }
    // 使用CustomConfirm组件
    confirmType.value = 1;
    confirmTitle.value = '删除确认';
    confirmMessage.value = '确认删除该商品吗？';
    confirmVisible.value = true;
}
const deleteAll  = () =>{
    // 使用CustomConfirm组件
    confirmType.value = 2;
    confirmTitle.value = '清空确认';
    confirmMessage.value = '确认清空所有商品吗？';
    confirmVisible.value = true;
    deleteGoodIndex.value = -1;
}
const confirmDelete = () => {
    if(confirmType.value == 1){
        // 删除单个商品
        allNum.value = new Decimal(0);
        allPrice.value = new Decimal(0);
        allListNum.value = 0;
        
        delete cartList.value[deleteGoodIndex.value];
        let cacheObj = cartList.value;
        cartList.value = {};
        let cacheKey = 0;
        for(let key in cacheObj){
            let thisGood = cacheObj[key];
            cartList.value[cacheKey] = thisGood;
            cacheKey++;
            if(thisGood.id != -2){
                allNum.value = new Decimal(allNum.value).add(new Decimal(thisGood.num)); 
                allPrice.value = new Decimal(allPrice.value).add(new Decimal(thisGood.thisAllPrice));
            }
        }
        allListNum.value = cacheKey;
    } else if(confirmType.value == 2){
        // 清空所有商品
        allNum.value = new Decimal(0);
        allPrice.value = new Decimal(0);
        allListNum.value = 0;
        cartList.value = {};
    } else if(confirmType.value == 3){
        // 现金结算
        orderMoneyPay();
    } else if(confirmType.value == 4){
        // 现金充值
        userMoneyRecharge();
    } else if(confirmType.value == 5){
        // 组合支付
        countPaySure();
    }
    
    deleteGoodIndex.value = -1;
    confirmVisible.value = false;
}

// 添加取消回调方法
const cancelDelete = () => {
    confirmVisible.value = false;
}
const rechargeConfirm = () =>{
    confirmType.value = 4;
    confirmTitle.value = '现金充值确认';
    confirmMessage.value = '确认现金充值吗？';
    confirmVisible.value = true;
}
const addCart = (index) =>{
    mp3.currentTime = 0; // 重置到音频开始位置
    mp3.play(); // 播放
    let thisGood = goodList.value[index];
    if(goodNumFromPort.value<= new Decimal(0) && thisGood.countType == 1){
        showModal('商品数量错误');
        return;
    }
    if(thisGood.countType == 2){
        goodNumFromPort.value = new Decimal(1);
    }
    if(goodNumFromPort.value > new Decimal(0)){
        let thisGoodPrice = new Decimal(0);
        if(userId.value>0){
            thisGoodPrice = thisGood.vipPrice;
        }else{
            thisGoodPrice = thisGood.price;
        }
        let ifHasGood = ref(false),thisCartListGoodKey = ref(''),thiscartListGood:any = ref({});
        for(let key in cartList.value){
            thiscartListGood = cartList.value[key];
            if(thisGood.id == thiscartListGood.id){
                ifHasGood.value = true;
                thisCartListGoodKey.value = key;
                break;
            }
        }
        if(ifHasGood.value == true){
            thiscartListGood.num = new Decimal(thiscartListGood.num).add(new Decimal(goodNumFromPort.value));
            thiscartListGood.thisAllPrice = thiscartListGood.num.mul(thisGoodPrice).toDP(2, Decimal.ROUND_DOWN);
            cartList.value[thisCartListGoodKey.value] = thiscartListGood;
            allNum.value = new Decimal(allNum.value).add(new Decimal(goodNumFromPort.value));
            allPrice.value = new Decimal(allPrice.value).add(new Decimal(goodNumFromPort.value).mul(thisGoodPrice));
            allPrice.value = allPrice.value.toDP(2, Decimal.ROUND_DOWN);
        }else{
            let thisGoodAllPrice = (new Decimal(goodNumFromPort.value).mul(new Decimal(thisGoodPrice))).toDP(2, Decimal.ROUND_DOWN);
            cartList.value[allListNum.value] = {
                    id:thisGood.id,
                    title:thisGood.title,
                    num:goodNumFromPort.value,
                    price:thisGoodPrice,
                    vipPrice:thisGood.vipPrice,
                    thisAllPrice:thisGoodAllPrice
            };
            allNum.value = new Decimal(allNum.value).add(new Decimal(goodNumFromPort.value));
            allPrice.value = new Decimal(allPrice.value).add(new Decimal(thisGoodAllPrice));
            allListNum.value++;
        }
    }
}

const userRecharge = async () =>{
    let bodyData = ref({});
    bodyData.value = {
        phone:phoneNum.value,
        num:rechargeNum.value,
        paytype:paytype.value,
        qcodeNum:qcode.value,
        isBpay:isBpay.value,
        givemoney:rechargeGiveNum.value
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    let res:any = await useApi('index/userRecharge',options); 
    if(res.code == 1){
        showModal('系统结算中，请稍后...');
        orderNumber.value = res.data.orderNumber;
        startPolling();
    }else{
        showModal(res.msg);
    }
}
const userMoneyRecharge = async () =>{
    let bodyData = ref({});
    bodyData.value = {
        phone:phoneNum.value,
        num:rechargeNum.value,
        paytype:5,
        isBpay:2,
        givemoney:rechargeGiveNum.value
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    let res:any = await useApi('index/userRecharge',options); 
    if(res.code == 1){
        orderNumber.value = res.data.orderNumber;
        payModel.value = 4;
        printPort();
        showModal('付款成功!');
        if(userId.value>0){
            search();
        }else{
            phoneNum.value = '';
        }
        isPaying.value = false;
        isBpay.value = 1;
    }else{
        showModal(res.msg);
    }
}
const startPolling = () =>{
    let times = ref(30);
    let timesIndex = ref(0);
    const timeId = setInterval(() => {
        if(timesIndex.value>=times.value){
            showModal('系统错误，请重试!');
            clearInterval(timeId);
        }
        getOrderStatus(timeId);
        timesIndex.value++;
    },1000)
}
const getOrderStatus = async (timeId) =>{
    let bodyData = ref({});
    bodyData.value = {
        orderNumber:orderNumber.value
    }
    if(orderNumber.value == ''){
        return;
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    let res:any = await useApi('index/getOrderStatus',options); 
    if(res.code == 1){
        var thisPayModel = payModel.value;
        printPort();
        clearInterval(timeId);
        showModal('付款成功!');
        if(userId.value>0){
            search();
        }else{
            phoneNum.value = '';
        }
        if(thisPayModel != 4){
            //不是充值支付时才清空数据
            clearAllData();
        }
        isPaying.value = false;
        isBpay.value = 1;
    }else if(res.code == 3){
        showModal(res.msg,30000);
    }else{
        clearInterval(timeId)
        showModal(res.msg);
    }
}
const clearAllData = () =>{
    userPayPassword.value = '';
    cartList.value = {};
    allPrice.value = new Decimal(0);
    allNum.value = new Decimal(0);
    orderNumber.value='';
    isPaying.value = false;
    allListNum.value = 0;
    deleteGoodIndex.value = -1;
    isBpay.value = 1;
}
const userRechargeGiveMoney = () =>{
    if(deleteGoodIndex.value == -1){
        showModal('请先选择赠送商品');
        return;
    }
    if(userId.value == 0){
        showModal('请先选择会员');
        return;
    }
    memberSearchShow.value = true;
    orderGiveMoney.value = '';
    rechargeInputType.value = 4;
}
const addOrderGiveMoney = () =>{
    if(orderGiveMoney.value == ''){
        showModal('请输入赠送数量');
        return;
    }
    if(deleteGoodIndex.value<0){
        showModal('请选择赠送商品');
        return;
    }
    if(new Decimal(orderGiveMoney.value).gt(new Decimal(userGiveMoney.value))){
        showModal('赠送数量不能大于剩余数量');
        return;
    }
    let thisGood = cartList.value[deleteGoodIndex.value];
    if(new Decimal(orderGiveMoney.value).gt(new Decimal(thisGood.num))){
        showModal('赠送数量不能大于商品数量');
        return;
    }
    thisGood.num = new Decimal(thisGood.num).sub(new Decimal(orderGiveMoney.value));
    let decMoney = new Decimal(orderGiveMoney.value).mul(new Decimal(thisGood.vipPrice));
    thisGood.thisAllPrice = new Decimal(thisGood.thisAllPrice).sub(decMoney);
    if(thisGood.thisAllPrice<0){
        thisGood.thisAllPrice = 0;
    }
    if(thisGood.num<0){
        thisGood.num = 0;
    }
    allPrice.value = new Decimal(allPrice.value).sub(decMoney);
    if(allPrice.value<new Decimal(0)){
        allPrice.value = new Decimal(0);
    }
    cartList.value[deleteGoodIndex.value] = thisGood;
    let giveGood = {};
    giveGood['id'] = -2;
    giveGood['title'] = '赠送('+thisGood.title+')';
    giveGood['num'] = new Decimal(orderGiveMoney.value);
    giveGood['price'] = 0;
    giveGood['vipPrice'] = 0;
    giveGood['thisAllPrice'] = new Decimal(0);
    cartList.value[allListNum.value++] = giveGood;
    orderGiveMoney.value = '';
}
const reBuildCartList = () =>{
    if(allListNum.value == 0){
        return;
    }
    allPrice.value = new Decimal(0);
    for(let key in cartList.value){
        let thisGood = cartList.value[key];
        if(thisGood.id == -2){
            continue;
        }
        let thisGoodNum = thisGood.num;
        let thisGoodAllPrice = new Decimal(thisGood.vipPrice).mul(new Decimal(thisGoodNum)).toFixed(2);
        thisGood.thisAllPrice = thisGoodAllPrice;
        thisGood.price = thisGood.vipPrice;
        cartList.value[key] = thisGood;
        if(thisGood.id != -2){
            allPrice.value = new Decimal(allPrice.value).add(thisGoodAllPrice); 
        }
    }
}
let changeNum = ref('');
let getOutShow = ref(false),getOutListData:any = ref({}),outListNum = ref(0);
const clearAllGetOut = async() => {
    getOutListData.value = {};
    outListNum.value=0;
    
    // 清除本地存储
    try {
        localStorage.removeItem('getOutListData');
        localStorage.removeItem('outListNum');
    } catch (e) {
        console.error('清除本地存储挂单数据失败:', e);
    }
    
    // 尝试清除服务器数据
    let bodyData = ref({});
    bodyData.value = {
        getOutListData:getOutListData.value,
        outListNum:outListNum.value
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    try {
        let res:any = await useApi('index/saveOrderGetOutData',options);
        showModal(res.msg);
    } catch (e) {
        console.error('服务器清除挂单数据失败:', e);
        showModal('网络连接失败，已清除本地数据');
    }
}
const getOrderGetOut = async() => {
    let bodyData = ref({});
    bodyData.value = {}
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    
    // 先尝试从本地存储获取数据
    let localOutListNum = 0;
    let localGetOutListData = {};
    try {
        const localOutListNumStr = localStorage.getItem('outListNum');
        const localGetOutListDataStr = localStorage.getItem('getOutListData');
        
        if (localOutListNumStr && localGetOutListDataStr) {
            localOutListNum = parseInt(localOutListNumStr);
            localGetOutListData = JSON.parse(localGetOutListDataStr);
        }
    } catch (e) {
        console.error('从本地存储获取挂单数据失败:', e);
    }
    
    try {
        // 尝试从服务器获取数据
        let res:any = await useApi('index/getOrderGetOutData',options);
        let serverOutListNum = parseInt(res.data.outListNum) ?? 0;
        let serverGetOutListData = res.data.getOutListData || {};
        
        // 合并服务器和本地数据
        if (localOutListNum > 0) {
            // 创建合并后的数据对象
            let mergedGetOutListData = { ...serverGetOutListData };
            let mergedOutListNum = serverOutListNum;
            
            // 将本地数据添加到合并数据中
            for (let key in localGetOutListData) {
                mergedGetOutListData[mergedOutListNum++] = localGetOutListData[key];
            }
            
            // 更新状态
            outListNum.value = mergedOutListNum;
            getOutListData.value = mergedGetOutListData;
            
            // 将合并后的数据同步回服务器
            let syncBodyData = ref({});
            syncBodyData.value = {
                getOutListData: mergedGetOutListData,
                outListNum: mergedOutListNum
            }
            const syncOptions:any = {
                headers: {
                    "Content-Type": "application/json",
                    "token":localStorage.getItem('token')
                },
                method: "POST",
                body:JSON.stringify(syncBodyData.value)
            };
            
            try {
                await useApi('index/saveOrderGetOutData', syncOptions);
                // 同步成功后清除本地存储
                localStorage.removeItem('getOutListData');
                localStorage.removeItem('outListNum');
                if (Object.keys(localGetOutListData).length > 0) {
                    showModal('本地挂单数据已同步到服务器', 1000);
                }
            } catch (e) {
                console.error('同步合并数据到服务器失败:', e);
            }
        } else {
            // 没有本地数据，直接使用服务器数据
            outListNum.value = serverOutListNum;
            getOutListData.value = serverGetOutListData;
        }
    } catch (e) {
        console.error('从服务器获取挂单数据失败:', e);
        // 服务器获取失败，使用本地数据
        if (localOutListNum > 0) {
            outListNum.value = localOutListNum;
            getOutListData.value = localGetOutListData;
            showModal('已从本地加载挂单数据', 1000);
        }
    }
}
getOrderGetOut();
const getOut = async() => {
    if(allNum.value<=new Decimal(0)){
        showModal('请选择商品',1000);
        return;
    }
    let thisDateObj = new Date();
    let dateStr = thisDateObj.getFullYear()+'-'+(thisDateObj.getMonth()+1)+'-'+thisDateObj.getDate()+' '+thisDateObj.getHours()+':'+thisDateObj.getMinutes()+':'+thisDateObj.getSeconds();
    let thisOutData:any = ref({});
    thisOutData.value.allNum = allNum.value;
    thisOutData.value.allPrice = allPrice.value;
    thisOutData.value.created_at = dateStr;
    thisOutData.value.userPhone = phoneNum.value;
    thisOutData.value.cartList = cartList.value;
    thisOutData.value.allListNum = allListNum.value;
    thisOutData.value.title = cartList.value[0].title;
    console.log(thisOutData.value);
    getOutListData.value[outListNum.value] = thisOutData.value;
    outListNum.value++;
    
    // 保存到本地存储
    try {
        localStorage.setItem('getOutListData', JSON.stringify(getOutListData.value));
        localStorage.setItem('outListNum', outListNum.value.toString());
    } catch (e) {
        console.error('本地存储挂单数据失败:', e);
    }
    
    // 尝试保存到服务器
    let bodyData = ref({});
    bodyData.value = {
        getOutListData:getOutListData.value,
        outListNum:outListNum.value
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    try {
        await useApi('index/saveOrderGetOutData',options);
    } catch (e) {
        console.error('服务器保存挂单数据失败:', e);
        showModal('网络连接失败，数据已保存在本地');
    }
    showModal('挂单完成',500);
    clearUser();
    clearAllData();
}
const getOutList = () =>{
    getOutShow.value = true;
}
const useGetOut = (index) => {
    let thisOutData:any = ref({});
    thisOutData.value = getOutListData.value[index];
    console.log(thisOutData.value.cartList);
    allNum.value = thisOutData.value.allNum;
    allPrice.value = thisOutData.value.allPrice;
    phoneNum.value = thisOutData.value.userPhone;
    cartList.value = thisOutData.value.cartList;
    allListNum.value = thisOutData.value.allListNum;
    delete getOutListData.value[index];
    outListNum.value--;
    let tmpgetOutListData = getOutListData.value,tmpIndex = 0;
    getOutListData.value = {};
    for(let key in tmpgetOutListData){
        getOutListData.value[tmpIndex] = tmpgetOutListData[key];
        tmpIndex++;
    }
    
    // 更新本地存储
    try {
        localStorage.setItem('getOutListData', JSON.stringify(getOutListData.value));
        localStorage.setItem('outListNum', outListNum.value.toString());
    } catch (e) {
        console.error('本地存储挂单数据失败:', e);
    }
    
    // 尝试更新服务器数据
    let bodyData = ref({});
    bodyData.value = {
        getOutListData:getOutListData.value,
        outListNum:outListNum.value
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    useApi('index/saveOrderGetOutData',options).catch(e => {
        console.error('服务器更新挂单数据失败:', e);
    });
    
    getOutShow.value = false;
    if(phoneNum.value != '' && phoneNum.value!=undefined){
        search();
    }
}
// 添加数字键盘相关方法
// 处理数字键盘输入
const handleKeyboardInput = (value) => {
    if(rechargeInputType.value == 1){
        phoneNum.value = value;
    } else if(rechargeInputType.value == 2){
        rechargeNum.value = value;
    } else if(rechargeInputType.value == 3){
        rechargeGiveNum.value = value;
    } else if(rechargeInputType.value == 4){
        orderGiveMoney.value = value;
    } else if(rechargeInputType.value == 5){
        userPayPassword.value = value;
    } else if(rechargeInputType.value == 7){
        changeNum.value = value;
    }
}

// 处理数字键盘确认
const handleKeyboardConfirm = (value) => {
    if(rechargeInputType.value == 1){
        phoneNum.value = value;
        search();
        memberSearchShow.value = false;
    } else if(rechargeInputType.value == 2 || rechargeInputType.value == 3){
        if(isBpay.value == 1){
            goPay(4);
        }else{
        	rechargeConfirm();
        }
    } else if(rechargeInputType.value == 4){
        orderGiveMoney.value = value;
        addOrderGiveMoney();
        memberSearchShow.value = false;
    } else if(rechargeInputType.value == 5){
        userPayPassword.value = value;
        if(payModel.value != 5) {
            memberGoPay();
        } else {
            countpay();
        }
        memberSearchShow.value = false;
    } else if(rechargeInputType.value == 7){
        changeNum.value = value;
        changeSure();
        memberSearchShow.value = false;
    }
}
const handleGiveInput = (value) => {
    if(rechargeInputType.value == 2) {
        // 如果当前是充值金额输入，保存充值金额并切换到赠送金额
        rechargeNum.value = value;
        rechargeInputType.value = 3;
    } else if(rechargeInputType.value == 3) {
        // 如果当前是赠送金额输入，保存赠送金额并切换到充值金额
        rechargeGiveNum.value = value;
        rechargeInputType.value = 2;
    }
}
// 处理数字键盘取消
const handleKeyboardCancel = () => {
    memberSearchShow.value = false;
}
</script> 
<template>
	<main class="homemain">
        <input 
            ref="hiddenInputRef"
            v-model="hiddenInput"
            @keydown="handleKeyDown"
            class="hidden-input"
            type="text"
            autocomplete="off"
            style="position: absolute; opacity: 0; pointer-events: auto; height: 0; width: 0; border: none; outline: none;"
        />
        <msgModal ref="msgModalRef"/>
        <CustomConfirm 
            :visible="confirmVisible"
            :title="confirmTitle"
            :message="confirmMessage"
            confirm-text="确定"
            cancel-text="取消"
            @confirm="confirmDelete"
            @cancel="cancelDelete"
        />
        <NumericKeyboard
            :allowDecimal="rechargeInputType != 5" 
            v-model:visible="memberSearchShow"
            :key="rechargeInputType" 
            :initial-value="rechargeInputType == 2 ? rechargeNum : (rechargeInputType == 3 ? rechargeGiveNum : (rechargeInputType == 4 ? orderGiveMoney : (rechargeInputType == 7 ? changeNum : (rechargeInputType == 5 ? userPayPassword : (rechargeInputType == 1 ? phoneNum : '')))))"
            :title="rechargeInputType == 1 ? '请输入手机号码' : (rechargeInputType == 2 ? '请输入充值金额' : (rechargeInputType == 3 ? '请输入赠送额度' : (rechargeInputType == 4 ? '请输入赠送数量' : (rechargeInputType == 7 ? '请输入金额' : (rechargeInputType == 5 ? '请输入密码' : '')))))"
            :placeholder="rechargeInputType == 1 ? '请输入手机号' : (rechargeInputType == 2 ? '请输入充值金额' : (rechargeInputType == 3 ? '请输入赠送额度' : (rechargeInputType == 4 ? '请输入赠送数量' : (rechargeInputType == 7 ? '请输入金额' : (rechargeInputType == 5 ? '请输入密码' : '')))))"
            :is-password="rechargeInputType == 5"
            :showGiveInput="rechargeInputType == 2 || rechargeInputType == 3"
            :showPayType="rechargeInputType == 2 || rechargeInputType == 3"
            :payTypeValue="isBpay"
            :giveValue="rechargeInputType == 2 ? rechargeGiveNum : rechargeNum"
            @update:payTypeValue="isBpay = $event"
            @input="handleKeyboardInput"
            @confirm="handleKeyboardConfirm"
            @cancel="handleKeyboardCancel"
            @giveInput="handleGiveInput"
            />

        <Transition name="getOutListfade">
            <div class="outlist" v-show='getOutShow'>
                <table class="outorderinfo">
                    <thead class="outheaderinfo">
                        <tr class="tr">
                            <td class="title">内容</td>
                            <td class="title">会员</td>
                            <td class="title">数量</td>
                            <td class="title">金额</td>
                            <td class="title">时间</td>
                            <td class="operation">操作</td>
                        </tr>
                    </thead>
                    <tbody class="outforminfo">
                        <tr class="outdatatr" v-for="(data,index) in getOutListData" :key="index">
                            <td class="title">{{ data.title }}</td>
                            <td class="title">{{ data.userPhone }}</td>
                            <td class="title">{{ data.allNum }}</td>
                            <td class="title">{{ data.allPrice }}</td>
                            <td class="title">{{ data.created_at }}</td>
                            <td class="operation">
                                <el-button @click="useGetOut(index)" class="settlement-btn">恢复</el-button>
                            </td>
                        </tr>
                        <tr class="settlementtr">
                            <el-button @click="clearAllGetOut" class="settlement-btn">清空</el-button>
                            <el-button @click="getOutShow = false" class="settlement-btn">关闭</el-button>
                        </tr>
                    </tbody>
                </table>
            </div>
        </Transition>
		<div class="left">
            <div class="category-nav">
                <div 
                    v-for="(data, index) in cate" 
                    :key="index"
                    @click="changeCat(index)"
                    :class="['category-item', { 'active': cateId === index }]"
                >
                    {{ data.name }}
                </div>
                </div>

                <!-- 商品列表 -->
                <div class="goods-grid">
                    <div 
                        v-for="(data, index) in goodList" 
                        :key="index"
                        class="good-card"
                        @click="addCart(index)"
                    >
                    <div class="good-content">
                        <h3 class="title">{{ data.title }}</h3>
                        <div class="price-info">
                            <div class="original-price">原价：¥{{ data.price }}</div>
                            <div class="vip-price">会员价：¥{{ data.vipPrice }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="homemainright">
            <div class="header">
                <div class="search-container">
                    <div class="weight-input">
                        <el-input class="goodNumInput" v-model="goodNumFromPort" placeholder="0.00"></el-input>
                    </div>
                    <div class="phone-search">
                        <el-input class="rechargeInput" @click="memberSearchShow = true;rechargeInputType = 1;" v-model="phoneNum" placeholder="请输入手机号"></el-input>
                        <el-button type="primary" @click="search">
                        <el-icon><Search /></el-icon>
                        查询
                        </el-button>
                    </div>
                </div>
                <div class="member-info-container">
                    <div class="member-info">
                        <div class="info-row">
                            <span class="info-label">会员信息:</span>
                            <span class="info-value">{{ userTitle }}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">余额:</span>
                            <span class="info-value">{{ userMoney }}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">赠送额度:</span>
                            <span class="info-value">{{ userGiveMoney }}</span>
                        </div>
                    </div>
                    <div class="member-actions">
                        <el-button type="success" @click="userRechargeGiveMoney">
                        <el-icon><Present /></el-icon>
                        赠送
                        </el-button>
                        <el-button type="danger" @click="clearUser">
                        <el-icon><Delete /></el-icon>
                        清除
                        </el-button>
                    </div>
                </div>
            </div>
            <div class="cart-container">
                <div class="cart-header">
                    <span class="header-item">商品名称</span>
                    <span class="header-item">单价</span>
                    <span class="header-item">数量</span>
                    <span class="header-item">金额</span>
                </div>
                <div class="cart-items">
                    <div class="detail" v-bind:class="{ 'free': data.id == -2, 'selected': index == deleteGoodIndex }" 
                        v-for="(data,index) in cartList" :key="index" @click="deleteShow(index)">
                        <div class="item-details">
                            <div class="item-price">{{ data.title }}</div>
                            <div class="item-price">￥{{ data.price }}</div>
                            <div class="item-quantity">× {{ data.num }}</div>
                            <div class="item-total">{{ data.thisAllPrice }}</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="order-summary">
                <div class="summary-item">
                    <span class="summary-label">数量:</span>
                    <span class="summary-value">{{ allNum }}</span>
                </div>
                <div class="summary-item total-price" @click="memberSearchShow = true;rechargeInputType=7;">
                    <span class="summary-label">总计:</span>
                    <span class="summary-value">￥{{ allPrice }}</span>
                </div>
            </div>
            <div class="action-buttons">
                <div class="button-row">
                    <el-button type="primary" @click="isBpay=1;goPay(1)">
                        <el-icon><ShoppingCart /></el-icon>
                        结算
                    </el-button>
                    <el-button type="success" @click="memberRecharge">
                        <el-icon><Wallet /></el-icon>
                        充值
                    </el-button>
                    <el-button type="warning" @click="isBpay=2;goPay(1)">
                        <el-icon><Money /></el-icon>
                        现金
                    </el-button>
                    <el-button type="danger" @click="deleteThisGoods">
                        <el-icon><Delete /></el-icon>
                        删除
                    </el-button>
                    </div>
                    <div class="button-row">
                    <el-button type="info" @click="deleteAll">
                        <el-icon><Delete /></el-icon>
                        清空
                    </el-button>
                    <el-button type="success" @click="getOut">
                        <el-icon><Upload /></el-icon>
                        挂起
                    </el-button>
                    <el-button type="warning" @click="getOutList">
                        <el-icon><Document /></el-icon>
                        挂单
                    </el-button>
                    <el-button style="visibility: hidden;">占位</el-button>
                </div>
            </div>
        </div>
    </main>
</template>